import { defineStore } from 'pinia'
import { Client } from '@stomp/stompjs'
import { useAuthStore} from '@/stores/authStore'
import {ChatAip} from "@/api/chat/index.js";


export const useChatSimpleStore = defineStore('chatSimple', {
    state: () => ({
        connectionStatus: 'disconnected', // 'connecting' | 'connected' | 'disconnected' | 'error'
        // STOMP客户端
        stompClient: null,
        // 订阅的主题
        subscribedTopics: [],
        // 订阅的私聊主题
        privateChatTopics: [
            //私聊消息频道
            '/queue/private',
            //消息回执频道
            '/queue/private/reply',
        ],
        // 订阅的群聊主题
        groupChatTopics: [
            //群聊消息频道
            '/queue/group',
            //消息回执频道
            '/queue/group/reply',
        ],
        // 订阅的系统主题
        systemTopics: [
            //系统消息频道
            '/queue/system',
            //消息回执频道
            '/queue/system/reply',
        ],
        //私聊消息
        privateChatMessages: [
            // "1":[
            //     {
            //         from: '1',
            //         to: '2',
            //         content: '你好',
            //         type: 'text',
            //         time: '2023-01-01 12:00:00',
            //         sender:'rec'
            //     }
            // ]
        ],
        //群聊消息
        groupChatMessages: [],
        //系统消息
        systemMessages: [],
        //好友列表
        friendList: [],
        //群聊列表
        groupList: [],
    }),
    actions: {
        connect() {
            const authStore = useAuthStore()
            const token = authStore.token
            if (!token) {
                console.error('未获取到有效token')
                return
            }

            if (this.connectionStatus === 'connected' || this.connectionStatus === 'connecting') return;

            this.connectionStatus = 'connecting';

            // 创建客户端时直接在配置中定义事件处理器
            this.stompClient = new Client({
                brokerURL: 'ws://localhost:9998/ws',
                connectHeaders: { Authorization: `Bearer ${token}` },
                debug: (str) => console.log('[DEBUG]', str),
                reconnectDelay: 5000,
                heartbeatIncoming: 4000,
                heartbeatOutgoing: 4000,

                onConnect: (frame) => {
                    console.log('[chatSimpleStore]', '连接成功', frame);
                    this.connectionStatus = 'connected';
                    this.subscribe();
                    this.subscribePrivateChat()
                    this.subscribeGroupChat('1')
                    this.subscribeOfflineMessages();

                    this.getFriendList();

                    this.getOfflineMessages();


                },

                onDisconnect: () => {
                    console.log('[chatSimpleStore]', '连接断开');
                    this.connectionStatus = 'disconnected';
                    this.unsubscribe();
                },

                onStompError: (frame) => {
                    console.error('[chatSimpleStore]', '连接失败', frame);
                    this.connectionStatus = 'error';
                }
            });

            this.stompClient.activate();
        },
        //取消订阅
        unsubscribe() {
            if (this.connectionStatus !== 'connected') return
            this.stompClient.unsubscribe('/topic/messages')
        },
        //定义接收方法
        subscribe() {
            if (this.connectionStatus !== 'connected') return
            this.stompClient.subscribe('/topic/messages', (message) => {
                console.log('[chatSimpleStore]', '收到消息', message.body)
            })
        },
        //定义发送方法
        send(message) {
            if (this.connectionStatus !== 'connected') return
            this.stompClient.publish({
                destination: '/app/chat',
                body: JSON.stringify({
                    content: message
                })
            })
        },
        //订阅私聊
        subscribePrivateChat() {
            if (this.connectionStatus !== 'connected') return
            this.stompClient.subscribe(`/user/queue/private`, (message) => {
                console.log('[chatSimpleStore]', '收到私聊消息', message.body)
                this.formatPrivateChatMessage(message.body)
            })
            this.stompClient.subscribe(`/user/queue/private/reply`, (message) => {
                console.log('[chatSimpleStore]', '收到私聊回执', message.body)
            })
        },
        //发送消息给某个用户
        sendToUser(message, userId) {
            if (this.connectionStatus !== 'connected') return
            this.stompClient.publish({
                destination: `/app/chat/user/${userId}`,
                body: JSON.stringify({
                    content: message
                })
            })
        },
        //订阅群聊
        subscribeGroupChat(groupId) {
            if (this.connectionStatus !== 'connected') return
            this.stompClient.subscribe(`/group/group/${groupId}`, (message) => {
                console.log('[chatSimpleStore]', '收到群聊消息', message.body)
                let msg = JSON.parse(message.body)
                msg.sender = 'received'

                if (!this.groupChatMessages[msg.from]) {
                    this.groupChatMessages[msg.from] = []
                }
                this.groupChatMessages[msg.from].push(msg)
            })
        },
        //发送消息给某个群
        sendToGroup(message, groupId) {
            if (this.connectionStatus !== 'connected') return
            this.stompClient.publish({
                destination: `/app/chat/group/${groupId}`,
                body: JSON.stringify({
                    content: message
                })
            })
        },
        //获取离线消息
        getOfflineMessages() {
            if (this.connectionStatus !== 'connected') return
           this.stompClient.publish({
                destination: `/app/chat/user/offline`,
                body: JSON.stringify({
                    content: '获取离线消息'
                })
            })
        },
        //订阅离线消息频道 /topic/private/offline
        subscribeOfflineMessages() {
            if (this.connectionStatus !== 'connected') return
            this.stompClient.subscribe(`/user/queue/private/offline`, (message) => {
                console.log('[chatSimpleStore]', '收到离线消息')
                this.formatPrivateChatMessage(message.body)
            })
        },
        //定义断开连接方法
        disconnect() {
            if (this.connectionStatus !== 'connected') return
            this.stompClient.deactivate()
        },
        //获取好友列表
        async getFriendList() {
            if (this.connectionStatus !== 'connected') return
            const res = await ChatAip.friendList()
            if (res.code === 200) {
                console.log('[chatSimpleStore]', '获取好友列表成功', res.data)
                this.friendList = res.data
            }
        },
        formatPrivateChatMessage(mesage){
            let msg = JSON.parse(mesage)
            msg.sender = 'received'
            if (!this.privateChatMessages[msg.from]) {
                this.privateChatMessages[msg.from] = []
            }
            this.privateChatMessages[msg.from].push(msg)
        }
    },
})